// sUndefined = require('lodash/isUndefined')
const isNumber = require('lodash/isNumber')
const cloud = require('wx-server-sdk')
const appid = process.env.appid //你的小程序appid
const secret = process.env.secretkey //你的小程序secret

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const ERROR_MSG = {
    500: '服务器错误',
    401: '登录过期',
    404: '未找到资源',
    4001: '重复提交'
}
class CustomError extends Error {
    constructor(code, msg) {
        super()
        this.code = code || 500
        this.msg = msg || ERROR_MSG[code] || 'unknown error'
    }
    getCodeMsg() {
        return {
            code: this.code,
            msg: this.msg
        }
    }
}
// 增加额外command功能
const _ = db.command
// 1. 获取数据库引用
const TcbRouter = require('tcb-router')

exports.main = async (event, context) => {


    const app = new TcbRouter({ event })
    const { OPENID, UNIONID } = cloud.getWXContext()


    app.use(async (ctx, next) => {
        //适用于所有的路由
        ctx.data = {} //声明data为一个对象
        try {
            ctx.body = {}
            ctx.body.code = 0
            await next()
        } catch (err) {
            console.log(err, 'err'.repeat(10))
            console.log(ctx)
            if (err instanceof CustomError) {
                const res = err.getCodeMsg()
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            } else if (err instanceof Error) {
                console.log(err)
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err.message
            } else if (typeof err === 'string') {
                ctx.body = {}
                ctx.body.code = 500
                ctx.body.msg = err
            } else {
                ctx.body = {}
                ctx.body.code = res.code || 500
                ctx.body.msg = res.msg
            }
        }
    })

    if (event.event === null) {
        const MAX_LIMIT = 100
        try {
            // 官方文档
            // 先取出集合记录总数
            // const countResult = await db.collection("enroll").count()
            // const total = countResult.total

            // // 计算需分几次取
            // const batchTimes = Math.ceil(total / 100)
            // // 承载所有读操作的 promise 的数组
            // const tasks = []
            // for (let i = 0; i < batchTimes; i++) {
            //     const promise = db.collection("enroll").skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
            //     tasks.push(promise)
            // }

            // // 等待所有
            // return (await Promise.all(tasks)).reduce((acc, cur) => {
            //     return {
            //         data: acc.data.concat(cur.data),
            //         errMsg: acc.errMsg,
            //     }
            // })
            // 方法2
            // 1，获取数据的总个数
            let count = await db.collection('enroll').count()
            count = count.total
            // 2，通过for循环做多次请求，并把多次请求的数据放到一个数组里
            let all = []
            for (let i = 0; i < count; i += 100) { //自己设置每次获取数据的量
                let list = await db.collection('enroll').skip(i).get()
                all = all.concat(list.data);
            }
            // 3,把组装好的数据一次性全部返回
            return all;
        } catch (error) {
            console.log("审核数据导出失败:", error)
        }
    }

    //添加营养师注册所需的东西
    app.router('Dietitian', async (ctx, next) => {
        const { enroll_name,
            enroll_idCard,
            enroll_phone,
            qualification,
            openid } = event.dietitian.current[0]
        try {
            await db.collection('enroll').add({
                // data 字段表示需新增的 JSON 数据
                data: {
                    enroll_name: enroll_name,
                    enroll_phone: enroll_phone,
                    enroll_idCard: enroll_idCard,
                    qualification: qualification,
                    openid: openid,
                    time: new Date(),
                },
                success: function (res) {
                    // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                    return res
                }
            })

        } catch (error) {
            if (error instanceof CustomError) {
                throw error
            }
            if (error instanceof Error) {
                console.log(error)
                throw new CustomError(500, error.message)
            } else if (typeof error === 'string') {
                throw new CustomError(500, error)
            }
        }
    })

    //从审核表中导出所有需要审核的数据
    app.router('find', async (ctx, next) => {
        const MAX_LIMIT = 100
        try {
            // 官方文档
            // 先取出集合记录总数
            const countResult = await db.collection("enroll").count()
            const total = countResult.total

            // 计算需分几次取
            const batchTimes = Math.ceil(total / 100)
            // 承载所有读操作的 promise 的数组
            const tasks = []
            for (let i = 0; i < batchTimes; i++) {
                const promise = db.collection("enroll").skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
                tasks.push(promise)
            }
            console.log("tasks:", tasks)
            // 等待所有
            return (await Promise.all(tasks)).reduce((acc, cur) => {
                return {

                    data: acc.data.concat(cur.data),
                    errMsg: acc.errMsg,
                }
            })
        } catch (error) {
            console.log("审核数据导出失败:", error)
        }
    })

    //审核成功后，从login中获取现在申请营养师的基本信息
    app.router('findDietitian', async (ctx, next) => {
        const { openid } = event.dietitian_info
        try {
            await db.collection("login").where({
                OPENID: openid
            }).get().then(res => {
                //返回值
                return res
            })
        } catch (error) {
            console.log("查找数据失败", error)
        }
    })

    //修改用户表里该注册人员的用户类型
    app.router('updateOccupation', async (ctx, next) => {
        const { openid } = event
        // return openid
        try {
            //认证通过后修改该用户的用户类型
            await db.collection("login").where({
                openId: openid
            }).update({
                data: {
                    occupation: "营养师"
                }
            }).then(() => {
                // 从审核表中找到认证信息
                db.collection("enroll").where({
                    openid: openid
                }).get().then(res => {
                    if (res.data) {
                        // 把认证通过的全部信息保存在营养师表中
                        db.collection("Audit").add({
                            data: {
                                name: res.data[0].enroll_name,
                                phone: res.data[0].enroll_phone,
                                idCard: res.data[0].enroll_idCard,
                                picture: res.data[0].qualification,
                                openid: openid,
                                time: new Date()
                            }
                        }).then(() => {
                            //完成对认证成功的数据 保存时，把审核表对应的数据进行删除
                            db.collection("enroll").where({
                                openid: openid
                            }).remove().then(() => {
                                console.log("删除成功.")
                            })
                        })
                    } else {
                        return errMsg
                    }

                })
            })
        } catch (error) {
            console.log("更新失败", error)
        }
    })

    //注册营养师失败后将会后审核表中删除之前的保存记录
    app.router('removeOccupation', async (ctx, next) => {
        const { openid } = event
        try {
            await db.collection("enroll").where({
                openid: openid
            }).remove().then(() => {
                console.log("删除成功.")
            })
        } catch (error) {
            console.log("删除失败:", error)
        }
    })

    return app.serve()
}